<script setup lang="ts">
import { computed, defineAsyncComponent, ref, onMounted, Component, h } from 'vue';
import { IconSvg, PromptStore, SvgIcon } from '@/components/common';
import { getConfigKey } from '@/api/user';
import { useBasicLayout } from '@/hooks/useBasicLayout';
const { isMobile } = useBasicLayout();
import { removeToken } from '@/store/modules/auth/helper';
import { NTooltip, useMessage, NAvatar, NPopover, NMenu, NIcon, NButton } from 'naive-ui';
import { homeStore, useChatStore, useUserStore } from '@/store';
import { loginOut, getUserInfo } from '@/api/user';
import { UserData } from '@/typings/user';
import { defaultSetting, UserInfo } from '@/store/modules/user/helper';
import { useRouter } from 'vue-router';
import { getToken } from '@/store/modules/auth/helper';
import to from 'await-to-js';
import { Settings as settings, Storefront as storefront, LogOut as out } from '@vicons/ionicons5';
import { ElMessageBox, ElLoading } from 'element-plus';
import avatarImg from '@/assets/avatar.jpg';

const chatStore = useChatStore();
//import gallery from '@/views/gallery/index.vue'

const Setting = defineAsyncComponent(() => import('@/components/common/Setting/index.vue'));

const st = ref({ show: false, showImg: false, menu: [], active: 'chat' });
const router1 = useRouter();
// const userInfo = ref<UserInfo>(defaultSetting().userInfo);
const userStore = useUserStore();

const userInfo = computed(() => userStore.userInfo);
const message = useMessage();
const show = ref(false);
const urouter = useRouter(); //

// 检查微信登录状态
const checkWechatLogin = () => {
  const msgprofile = localStorage.getItem('msgprofile');
  if (!msgprofile) {
    message.warning('请先登录微信后再操作');
    urouter.push('/wechat');
    return false;
  }
  return true;
};

const isLogin = computed(() => {
  return localStorage.getItem('TOKEN');
});

import { router } from '@/router';

const goHome = computed(() => {
  return router.currentRoute.value.name;
});
const goHomeIncludes = computed(() => {
  return router.currentRoute.value.path;
});

onMounted(() => {
  getLoginUserInfo();
});

/**
 * 获取当前登录用户信息
 */
async function getLoginUserInfo() {
  // 用户未登录,不需要获取用户信息
  if (!getToken()) {
    return;
  }
  const [err, newUserInfo] = await to(getUserInfo<UserData>());
  if (err) {
    // message.error(err.toString())
    console.log(err.toString());
  }
  if (newUserInfo) {
    userInfo.value.avatar = newUserInfo.data.user.avatar;
    userInfo.value.name = newUserInfo.data.user.nickName;
    userInfo.value.userBalance = newUserInfo.data.user.userBalance;
    userInfo.value.userName = newUserInfo.data.user.userName;
    isLogin.value = true;
  }
  if (!userInfo.value.avatar) {
    userInfo.value.avatar = avatarImg;
  }
}

const chatId = computed(() => chatStore.active ?? '1002');
/**
 * 退出登录
 */
async function handleReset() {
  await loginOut();
  // 删除用户token
  removeToken();
  // 清除相关缓存
  localStorage.removeItem('wxLogin');
  localStorage.removeItem('userInfo');
  localStorage.removeItem('msgprofile');
  localStorage.removeItem('userStorage');
  // 跳转到登录页面
  router1.push('/login');
}

async function longin() {
  // 跳转到登录页面
  router1.push('/login');
}

function renderIcon(icon: Component) {
  return () => h(NIcon, null, { default: () => h(icon) });
}

const menuOptions = ref([
  {
    label: '账号设置',
    key: 'accountSettings',
    icon: renderIcon(settings)
  },
  // {
  //   label: '购买套餐',
  //   key: 'buy',
  //   icon: renderIcon(storefront)
  // },
  {
    label: '退出账号',
    key: 'logout',
    icon: renderIcon(out)
  }
]);

const handleSelect = (key: string) => {
  if (key === 'accountSettings') {
    st.value.show = true;
  } else if (key === 'logout') {
    handleLogoutConfirm();
  } else if (key === 'buy') {
    show.value = true;
  }
};

// 退出账号确认处理
const handleLogoutConfirm = async () => {
  try {
    await ElMessageBox.confirm('确定要退出账号吗？', '退出账号', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const loading = ElLoading.service({
      lock: true,
      text: '正在退出...',
      background: 'rgba(255, 255, 255, 0.7)'
    });

    await handleReset();
    loading.close();
  } catch {
    // 用户取消操作
  }
};
</script>
<template>
  <div class="flex-shrink-0 w-[80px] z-[1000] h-full" v-if="!isMobile" data-tauri-drag-region>
    <div class="flex h-full select-none flex-col items-center justify-between bg-[#e8eaf1] px-2 pt-4 pb-8 dark:bg-[#25272d]">
      <div class="flex flex-col space-y-4 flex-1" data-tauri-drag-region>
        <a
          @click="urouter.push(`/home`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHome == 'home' ? 'active' : '']">
                <SvgIcon icon="ri:home-line" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            数据总量
          </n-tooltip>
        </a>
        <a
          @click="urouter.push(`/wechat`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHome == 'jlweChat' ? 'active' : '']">
                <SvgIcon icon="ri:wechat-fill" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            微信
          </n-tooltip>
        </a>
        <a
          @click="checkWechatLogin() && urouter.push(`/userRate/tagManage`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHomeIncludes.includes('userRate') ? 'active' : '']">
                <SvgIcon icon="ri-customer-service-2-fill" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            客户转化
          </n-tooltip>
        </a>
        <a
          @click="checkWechatLogin() && urouter.push(`/friendSocial/sendSocial`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHomeIncludes.includes('friendSocial') ? 'active' : '']">
                <SvgIcon icon="ri-camera-lens-line" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            朋友圈营销
          </n-tooltip>
        </a>
        <a
          @click="checkWechatLogin() && urouter.push(`/userMange/customerPool`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHomeIncludes.includes('userMange') ? 'active' : '']">
                <SvgIcon icon="ri-user-settings-line" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            客户管理
          </n-tooltip>
        </a>
        <a
          @click="checkWechatLogin() && urouter.push(`/privateModel/aiTrain`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHomeIncludes.includes('privateModel') ? 'active' : '']">
                <SvgIcon icon="ri-git-repository-private-line" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            企业私有模型
          </n-tooltip>
        </a>
        <a
          v-if="userStore.adminRule === 'admin'"
          @click="checkWechatLogin() && urouter.push(`/companyMange/staffMange`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHomeIncludes.includes('companyMange') ? 'active' : '']">
                <SvgIcon icon="ri-building-2-line" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            企业管理
          </n-tooltip>
        </a>
        <!-- <a
          @click="
            st.active = 'chat';
            urouter.push(`/chat`);
          "
          class="router-link-active router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col" :class="[goHome == 'Chat' ? 'active' : '']">
                <SvgIcon icon="ri:chat-history-line" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            对话
          </n-tooltip>
        </a>

        <a
          @click="urouter.push(`/store`)"
          class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]"
        >
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col">
                <SvgIcon icon="ri:apps-fill" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            应用中心
          </n-tooltip>
        </a>

        <a class="router-link-exact-active h-12 w-12 cursor-pointer rounded-xl bg-white duration-300 dark:bg-[#34373c] hover:bg-[#bbb] dark:hover:bg-[#555]">
          <n-tooltip placement="right" trigger="hover">
            <template #trigger>
              <div class="flex h-full justify-center items-center py-1 flex-col">
                <SvgIcon icon="weui:shop-filled" class="text-3xl flex-1"></SvgIcon>
              </div>
            </template>
            插件市场
          </n-tooltip>
        </a> -->
      </div>
      <div class="flex flex-col space-y-2">
        <!-- <NAvatar v-show="isLogin" size="large" round :src="userInfo.avatar" v-if="userInfo.avatar" :fallback-src="defaultAvatar" class="cursor-pointer" /> -->

        <n-popover trigger="click" :show-arrow="false">
          <template #trigger>
            <div class="flex flex-col items-center space-y-1">
              <n-avatar v-show="isLogin" size="large" round :src="userInfo.avatar" />
              <div v-show="isLogin" class="text-xs text-gray-600 dark:text-gray-400 truncate max-w-[60px] text-center">
                {{ userInfo.name }}
              </div>
            </div>
          </template>
          <n-menu :options="menuOptions" @select="handleSelect" />
        </n-popover>

        <div v-show="!isLogin" class="user-bottom" @click="longin">
          <n-button tertiary type="info"> 登录 </n-button>
        </div>
      </div>
    </div>
  </div>
  <Setting v-if="st.show" v-model:visible="st.show" />
  <!-- <PromptStore v-model:visible="show" title="购买套餐"></PromptStore> -->
</template>
